package cn.wolfcode.shop.web.controller;

import cn.wolfcode.shop.alipay.AlipayProperties;
import cn.wolfcode.shop.anno.UserParam;
import cn.wolfcode.shop.common.BusinessException;
import cn.wolfcode.shop.domain.OrderInfo;
import cn.wolfcode.shop.domain.User;
import cn.wolfcode.shop.mapper.OrderInfoMapper;
import cn.wolfcode.shop.mapper.SeckillOrderMappaer;
import cn.wolfcode.shop.msg.SeckillServerCodeMsg;
import cn.wolfcode.shop.service.IOrderInfoService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@RestController
@RequestMapping("/api/pay")
@Slf4j
public class AlipayController {

    @Autowired
    private AlipayProperties properties;
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    /**
     * 异步通知支付结果，如果处理成功需要返回 "success" 字符串给SDK
     *
     * @param params
     * @return
     * @throws Exception
     */
    @RequestMapping("/notify_url")
    public String notifyUrl(@RequestParam HashMap<String, String> params) throws Exception {
        boolean signVerified = AlipaySignature.rsaCheckV1(params, properties.getAlipayPublickey(),
                properties.getCharset(), properties.getSigntype()); //调用SDK验证签名

        if (signVerified) {//验证成功
            //商户订单号
            String out_trade_no = params.get("out_trade_no");
            //支付宝交易号
            String trade_no = params.get("trade_no");
            //交易状态
            String trade_status = params.get("trade_status");
            if (trade_status.equals("TRADE_FINISHED")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知

                int ret = orderInfoMapper.updatePaySuccess(out_trade_no); // 验证成功，修改订单状态
                log.info("------------》执行异步回调通知用户：修改结果{}《-------------", ret);
                if (ret > 0) {
                    // 更新成功
                    // 保存支付流水
                    // 保存发货订单
                    // 保存用户积分
                    // 等操作
                    log.info("订单状态是已支付之后，做一些其他的业务操作：积分账单发票等");
                }
            }
            return ("success");
        } else {//验证失败
            return ("fail");
            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }
    }

    /**
     * 同步回调地址，用户知否成功之后重新跳转到更改了订单状态的订单详情的界面
     *
     * @param params
     * @param resp
     * @throws AlipayApiException
     * @throws IOException
     */
    @RequestMapping("/return_url")
    public void returnUrl(@RequestParam HashMap<String, String> params, HttpServletResponse resp) throws Exception {
        boolean signVerified = AlipaySignature.rsaCheckV1(params, properties.getAlipayPublickey(),
                properties.getCharset(), properties.getSigntype()); //调用SDK验证签名

        if (signVerified) {
            //商户订单号： out_trade_no对应的是我们自己的订单号orderNo
            String out_trade_no = params.get("out_trade_no");

            //支付宝交易号
            String trade_no = params.get("trade_no");

            //付款金额
            String total_amount = params.get("total_amount");

            log.info("------------》执行同步回调通知用户《-------------");

            // 支付成功：重定向到详情页面
            resp.sendRedirect("http://localhost/order_detail.html?orderNo=" + out_trade_no);
        } else {
            // 支付失败：重定向到错误页面
            resp.sendRedirect("http://localhost/error.html");
        }
    }

    /**
     * 调用阿里沙箱SDK支付功能
     *
     * @param orderNo
     * @param user
     * @return
     * @throws AlipayApiException
     */
    @RequestMapping
    public String pay(String orderNo, @UserParam User user) throws AlipayApiException {
        //获得初始化的AlipayClient 通过配置类Bean注入的方式
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(properties.getReturnUrl());
        alipayRequest.setNotifyUrl(properties.getNotifyUrl());

        // 查询订单相关信息
        OrderInfo orderInfo = orderInfoService.findByIdAndUserId(orderNo, user.getId());
        if (orderInfo == null) {
            // 查不到报个错，应该返回CodeMsg给前台
            throw new BusinessException(SeckillServerCodeMsg.OPS_ERROR);
        }

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderNo;
        //付款金额，必填
        String total_amount = orderInfo.getSeckillPrice().toString();
        //订单名称，必填
        String subject = "WolfCode" + orderInfo.getGoodName();
        //商品描述，可空
        String body = orderInfo.getGoodName() + "商品秒杀价：" + orderInfo.getSeckillPrice();

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //响应
        return alipayClient.pageExecute(alipayRequest).getBody();
    }
}
